import { useLoginStore } from "@/stores/userInfo";
import type { Router } from "vue-router";
import { dynamicRoutes } from "./routes";

/**
 * 通用守卫配置
 * @param router
 */
function setupCommonGuard(router: Router) {
  router.beforeEach(async () => {});

  router.afterEach((to) => {
    document.title = to.meta.title as string;
  });

  // 防止浏览器刷新后出现404，(因为刷新后相当于项目重新运行，添加的动态路由就没了)
  router.isReady().then(() => {
    const userInfo = useLoginStore();
    if (userInfo.isAuthenticated) {
      dynamicRoutes.forEach((item) => {
        router.addRoute(item);
      });

      router.replace(router.currentRoute.value.fullPath);
    }
  });
}
/**
 * 权限访问守卫配置
 * @param router
 */
function setupAccessGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const userInfo = useLoginStore();
    if (userInfo.isAuthenticated) {
      if (to.path === "/auth/login") {
        ElMessage.info("您已登录，请先退出系统再进行登录");
        next({ path: "/dashboard/analytics" });
      } else {
        next();
      }
    } else {
      if (to.path === "/auth/login") {
        next();
      } else {
        next({ path: "/auth/login" });
      }
    }
  });
}

/**
 * 项目守卫配置
 * @param router
 */
function createRouterGuard(router: Router) {
  /** 通用 */
  setupCommonGuard(router);
  /** 权限访问 */
  setupAccessGuard(router);
}

export { createRouterGuard };
